package zjh_20230327;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DBUtils<T>{

    private String url;
    private String username;
    private String password;

    private Connection conn;
    private PreparedStatement ps;

    private ResultSet resultSet;
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
    DBUtils(String url,String username,String password){
        this.url = url;
        this.username = username;
        this.password = password;
    }

    /**
     * 获取连接
     * @return
     */
    private Connection getConnection(){
        if (url != null && username != null && password != null) {
            try {
                return DriverManager.getConnection(url, username, password);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        throw new NullPointerException("数据库连接参数为null");
    };

    /**
     * 增删改
     * @return
     */
    public int excuteUpdate(String sql,Object ...arr)  throws SQLException {
        conn = getConnection();
        ps= conn.prepareStatement(sql);
            for (int i = 0; i < arr.length; i++) {
                ps.setObject(i+1,arr[i]);
        }
        int i = ps.executeUpdate();
        return i;
    };

    public List<T> Select(String sql, Recover<T> recover, Object ...arr) throws SQLException {
        resultSet = excuteQuery(sql, arr);
        List<T> list = new ArrayList<>();
        while (resultSet.next()){
            list.add(recover.recover(resultSet));

        }
        return list;
    }

    /**
     * 查询
     * @return
     */
    public ResultSet excuteQuery(String sql ,Object ...arr) throws SQLException {
        conn = getConnection();
           ps= conn.prepareStatement(sql);
            for (int i = 0; i < arr.length; i++) {
                ps.setObject(i+1,arr[i]);
            }
        resultSet = ps.executeQuery();
        return resultSet;
    };

    public void close() throws SQLException {
        if (ps != null){
            ps.close();
        }
        if (conn != null){
            conn.close();
        }
    }
}
